package com.wangce.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.PageInfo;
import com.wangce.bean.Dim;
import com.wangce.bean.Order;
import com.wangce.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * ClassName: OrderController
 * Description:
 * date: 2021/11/15 9:53
 *
 * @author 凡人
 * @since JDK 1.8
 */
@Controller
public class OrderController {

    @Autowired
    OrderService service;

    /**
     * 列表
     * @param model
     * @param d
     * @param cur
     * @param size
     * @return
     */
    @RequestMapping("list")
    public String list(Model model, Dim d,
                       @RequestParam(defaultValue = "1") Integer cur,
                       @RequestParam(defaultValue = "3") Integer size){
        PageInfo<Order> list = service.list(d,cur,size);
        model.addAttribute("list",list);
        return "list";
    }

    /**
     * 去添加
     * @return
     */
    @RequestMapping("toAdd")
    public String toAdd(Model model){
        Snowflake snowflake = IdUtil.getSnowflake(31, 31);
        long l = snowflake.nextId();
        model.addAttribute("l",l);
        return "add";
    }

    /**
     * 添加
     * @return
     */
    @RequestMapping("add")
    public String add(Order order){
        Integer i = service.add(order);
        if(i>0){
            return "redirect:list";
        }
        return "add";
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping("toDelete")
    @ResponseBody
    public String toDelete(Integer[] id){
        Integer i = service.delete(id);
        if(i>0){
            return "ok";
        }
        return "no";
    }

    @RequestMapping("upFile")
    @ResponseBody
    public String upFile(MultipartFile file) throws IOException {
        if(file!= null && !file.isEmpty()){
            String name = file.getOriginalFilename();
            String suffx = name.substring(name.lastIndexOf("."));
            String newName = UUID.randomUUID() + suffx;
            file.transferTo(new File("d:/pic",newName));
            return "/pic/"+newName;
        }
        return null;
    }
}
